<script setup lang="ts">
import { getList } from '@/api/api-manage/approve'
import { useRenderIcon } from '@/components/ReIcon/src/hooks'
import useDateRangeParams from '@/hooks/useDateRangeParams'

import { usePagination } from '@/hooks/usePagination'
import { useTableHeight } from '@/hooks/useTableHeight'
import useDictStore from '@/store/modules/dict'
import { ModalShowType } from '@/types/common'
import { formatDate, omitEmptyValue } from '@/utils/common'
import apiApplicationModal from '@/views/api-manage/my-apply/api-application-modal.vue'
import Refresh from '@iconify-icons/ep/refresh'
import Search from '@iconify-icons/ep/search'
import { FormInstance } from 'element-plus'
import { reactive, ref } from 'vue'

defineOptions({
  name: 'api-manage/list',
})

const { api_apply_status } = useDictStore().getDicts('api_apply_status')
const searchParams = reactive({
  applyName: undefined,
  applyPerson: undefined,
  applyStatus: api_apply_status.getLabel('待审核'),
})
const formRef = ref<FormInstance>()
const applyStatus = ref('todo')
const searchDateRange = ref<[Date, Date]>([null, null])
const { dateRangeParams } = useDateRangeParams(searchDateRange, 'YYYY-MM-DD HH:mm:ss', (s, e) => ({
  'params[beginApplySubmitTime]': s,
  'params[endApplySubmitTime]': e,
}))
const { pagination, paginationParams, changePageNumber, changePageSize } = usePagination(onSearch)
const columns: TableColumnList = [
  {
    type: 'selection',
    width: 55,
    align: 'left',
  },
  {
    label: '申请单编号',
    prop: 'applyNo',
    minWidth: 100,
  },
  {
    label: '申请单名称',
    prop: 'applyName',
    minWidth: 150,
  },
  {
    label: '申请人',
    prop: 'applyPerson',
    minWidth: 150,
  },
  // {
  //   label: "申请类型",
  //   prop: "applyType",
  //   minWidth: 100,
  //   formatter({ applyType }) {
  //     return api_apply_type.getLabel(applyType);
  //   }
  // },
  {
    label: '申请提交时间 ',
    prop: 'applyStatus',
    minWidth: 180,
    formatter: ({ applySubmitTime }) => formatDate(applySubmitTime),
  },
  {
    label: '申请状态',
    prop: 'type',
    minWidth: 100,
    formatter({ applyStatus }) {
      return api_apply_status.getLabel(applyStatus)
    },
  },
  {
    label: '审批人',
    prop: 'operatePerson',
    minWidth: 100,
  },
  {
    label: '操作时间 ',
    prop: 'oprateTime',
    minWidth: 180,
    formatter: ({ oprateTime }) => formatDate(oprateTime),
  },
  {
    label: '操作',
    fixed: 'right',
    width: 180,
    slot: 'operation',
  },
]
const dataList = ref([])
const loading = ref(false)
const { tableHeight, tableRef } = useTableHeight()

/** 查询列表 */
async function onSearch() {
  loading.value = true
  const { rows, total } = await getList(
    omitEmptyValue({
      ...dateRangeParams.value,
      ...paginationParams.value,
      applyName: searchParams.applyName,
      applyPerson: searchParams.applyPerson,
      applyStatus: searchParams.applyStatus,
    })
  ).finally(() => {
    loading.value = false
  })
  dataList.value = rows
  pagination.total = total
}

function onFilterChange(value: string) {
  if (value === 'todo') {
    searchParams.applyStatus = api_apply_status.getLabel('待审核')
  } else {
    searchParams.applyStatus = undefined
  }
  onSearch()
}

/** 重置新增的表单  */
async function resetForm() {
  searchDateRange.value = [null, null]
  formRef.value.resetFields()
  onSearch()
}

const modalShow = ref(ModalShowType.Hide)
const termId = ref<number | null>(null)

onSearch()
</script>

<template>
  <div class="main table-view-layout">
    <el-form
      ref="formRef"
      :inline="true"
      :model="searchParams"
      class="bg-el-bg w-[99/100] pl-8 pt-4"
    >
      <el-form-item prop="applyName">
        <el-input
          v-model="searchParams.applyName"
          placeholder="请输入申请关键词"
          clearable
          style="width: 240px"
          @keyup.enter="onSearch"
        />
      </el-form-item>
      <el-form-item prop="applyPerson">
        <el-input
          v-model="searchParams.applyPerson"
          placeholder="请输入申请人"
          clearable
          style="width: 240px"
          @keyup.enter="onSearch"
        />
      </el-form-item>
      <el-form-item label="申请提交时间">
        <el-date-picker
          v-model="searchDateRange"
          unlink-panels
          type="datetimerange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        />
      </el-form-item>
      <el-form-item prop="applyStatus">
        <el-select
          v-model="searchParams.applyStatus"
          placeholder="申请状态"
          clearable
          class="!w-[180px]"
        >
          <el-option
            v-for="item in api_apply_status"
            :key="item.value"
            :label="item.label"
            :value="item.value"
            :disabled="
              applyStatus == 'todo' &&
              (item.label == '审核通过' || item.label == '审核拒绝' || item.label == '已撤销')
            "
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          :icon="useRenderIcon(Search)"
          :loading="loading"
          @click="onSearch"
        >
          搜索
        </el-button>
        <el-button :icon="useRenderIcon(Refresh)" @click="resetForm"> 重置 </el-button>
      </el-form-item>
    </el-form>
    <PureTableBar>
      <template #title>
        <div class="-mt-1">
          <el-radio-group v-model="applyStatus" @change="onFilterChange">
            <el-radio-button label="todo">待办申请</el-radio-button>
            <el-radio-button label="all">全部申请</el-radio-button>
          </el-radio-group>
        </div>
      </template>
      <template #table>
        <pure-table
          ref="tableRef"
          border
          align-whole="center"
          showOverflowTooltip
          table-layout="auto"
          :max-height="tableHeight"
          :loading="loading"
          :data="dataList"
          :columns="columns"
          :pagination="pagination"
          :header-cell-style="{
            background: 'var(--el-table-row-hover-bg-color)',
            color: 'var(--el-text-color-primary)',
          }"
          @page-size-change="changePageSize"
          @page-current-change="changePageNumber"
        >
          <template #operation="{ row }">
            <el-button
              link
              class="reset-margin"
              type="primary"
              @click="
                () => {
                  modalShow = ModalShowType.View
                  termId = row.applyId
                }
              "
            >
              查看
            </el-button>
            <el-button
              link
              class="reset-margin"
              type="primary"
              :disabled="row.applyStatus !== '0'"
              @click="
                () => {
                  modalShow = ModalShowType.Edit
                  termId = row.applyId
                }
              "
            >
              审批
            </el-button>
          </template>
        </pure-table>
      </template>
    </PureTableBar>
    <apiApplicationModal v-model:modalShow="modalShow" :term-id="termId" :on-search="onSearch" />
  </div>
</template>

<style scoped lang="scss">
:deep(.el-dropdown-menu__item i) {
  margin: 0;
}
</style>
